#coding=utf-8

#Auther: minorityee1984@gmail.com
#Date: 2011-7-28
#Purpose: emulating msg transporting

from msg_def import *
import sys
import time
import serial
import socket
import bin

usage = """usage: python emulatemsg.py -p [port] -b [baudrate] -t [times] -i [interval] -d [messageID] -a1 [argument1] -a2 [argument2] ...
   eg: python emulatemsg.py -p COM1 -b 115200 -t 100 -i 1 -d 0xc1 -a1 1 -a2 -360"""

g_port = 'COM1'
g_baudrate = 115200
g_bytesize = 8
g_parity = 'N'
g_stopbits = 1
g_timeout = None

g_ip = "127.0.0.1"
g_sport = 1729
g_sock = 0
g_listen = 0

def new_package(clientID, msgID, arg):
	if MSG_CMD_INIT == msgID:
		msg = pack_MsgInit()
	elif MSG_CMD_ACTIVATE_SCAN == msgID:
		msg = pack_MsgActivateScan(int(arg))
	elif MSG_CMD_ACTIVATE_ROTATE == msgID:
		msg = pack_MsgActivateRotate(int(arg[0]), int(arg[1]))
	else:
		print 'msgID:%d undefined' % msgID
		sys.exit(0)

	packHeader = pack_PackageHeader(clientID, len(msg))
	msgHeader = pack_MsgHeader(msgID)
	return packHeader + msgHeader + msg

def get_opt(argv):
	global g_port
	global g_baudrate
	global g_ip
	global g_sport
	global g_sock
	for i in range(1, len(argv)):
		if -1 != argv[i].find('-p'):
			g_port = argv[i + 1]
		elif -1 != argv[i].find('-b'):
			g_baudrate = int(argv[i + 1])
		elif -1 != argv[i].find('-t'):
			times = int(argv[i + 1])
		elif -1 != argv[i].find('-i'):
			interval = int(argv[i + 1])
		elif -1 != argv[i].find('-d'):
			msgID = int(argv[i + 1],16)
		elif -1 != argv[i].find('-h'):
			g_ip = argv[i + 1]
			g_sock = 1
		elif -1 != argv[i].find('-s'):
			g_sport = int(argv[i + 1])
		elif -1 != argv[i].find('-l'):
			g_listen = argv[i + 1]
			
	param = []
	for i in range(12, len(argv)):
		if 0 != i % 2:
			continue
		param.append(argv[i])
	return times, interval, msgID, param

def main(argv):
	if len(argv) < 3 or 0 == len(argv) % 2:
		print usage
		sys.exit(0)
	
	times, interval, msgID, param = get_opt(argv)
	if not times > 0:
		sys.exit(0)
	if 0 == g_sock:
		try:
			io = serial.Serial(g_port, g_baudrate, g_bytesize, g_parity, g_stopbits, g_timeout)
			
		except serial.SerialException, e:
			print e
			print usage
			sys.exit(1)
	elif 1 == g_sock:
		try:
			io = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		except socket.error, msg:
			print msg
			sys.exit(1)

		if 0 == g_listen: 
			io.connect((g_ip, g_sport))
		else:
			listenfd = io.bind((g_ip, g_sport))
			listenfd.listen(0x80)
			while True:
				sockfd = listenfd.accept()
				print sockfd.recv(1024)

	#send package
	for i in range(1, times):
		package = new_package(7, msgID, param)
		if 1 == g_sock:
			io.send(package)
		else:
			io.write(package)
		time.sleep(interval)
	io.close()
	
if __name__ == "__main__":
	main(sys.argv)
